package com.mayuanfei.springboot09.controller;

import cn.hutool.json.JSONUtil;
import com.mayuanfei.springboot09.pojo.SysUser;
import com.mayuanfei.springboot09.util.RedisUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * redisson测试controller
 *
 * @author 老马
 * @date 2023-06-13 13:19
 */
@RestController
public class RedissonTestController {

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/test1")
    public String testRedis1() {
        Map<String, Integer> map  = new HashMap<>();
        map.put("laoma", 44);
        map.put("cuidk", 43);
        RMap<Object, Object> lala = this.redissonClient.getMap("lala");
        lala.putAll(map);
        return JSONUtil.toJsonStr(lala);
    }

    //手动使用
    @GetMapping("/test2")
    public SysUser testRedis2(Long userid) {
        SysUser user = new SysUser(userid, "测试用户" + userid, "昵称" + userid);
        RBucket<SysUser> bucket = this.redissonClient.getBucket("user:" + userid);
        SysUser user1 = bucket.get();
        if(user1!=null){
            return user1;
        }
        bucket.set(user);
        RedisUtils.setCacheObject("springboot09:user:"+user.getUserId(), user);
        return user;
    }

    /**
     * 表示这个方法有了缓存的功能,方法的返回值会被缓存下来
     * 下一次调用该方法前,会去检查是否缓存中已经有值
     * 如果有就直接返回,不调用方法
     * 如果没有,就调用方法,然后把结果缓存起来
     * 这个注解「一般用在查询方法上」
     */
    @Cacheable(cacheNames = "test:demo", key = "#userid", condition = "#userid != null")
    @GetMapping("/test3")
    public SysUser testRedis3(Long userid) {
        SysUser user = new SysUser(userid, "测试用户" + userid, "昵称" + userid);
        return user;
    }

    /**
     * 会把方法的返回值put到缓存里面缓存起来,供其它地方使用
     * 它「通常用在新增或者实时更新方法上」
     */
    @CachePut(cacheNames = "test:demo", key = "#userid", condition = "#userid != null")
    @GetMapping("/test4")
    public SysUser testRedis4(Long userid) {
        SysUser user = new SysUser(userid, "测试用户" + userid, "昵称" + userid);
        return user;
    }

    /**
     * 使用了CacheEvict注解的方法,会清空指定缓存
     * 「一般用在删除的方法上」
     */
    @CacheEvict(cacheNames = "test:demo", key = "#userid", condition = "#userid != null")
    @GetMapping("/test5")
    public String testRedis5(Long userid) {
        return "删除成功";
    }
}